package cn.itcast.bos.realm;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.PermissionService;
import cn.itcast.bos.service.system.RoleService;
import cn.itcast.bos.service.system.UserService;

//@Service("bosRealm"),IOC在shiro配置文件中
public class BosRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private PermissionService permissionService;
	
	@Override
	// 授权...
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalcollection) {
		System.out.println("授权.............");
		//创建一个SimpleAuthorizationInfo对象
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		//获取subject
		Subject subject = SecurityUtils.getSubject();
		//获取subject中的user对象
		User user = (User) subject.getPrincipal();
		
		//根据user来查找这个user对应的角色
		List<Role> roles = roleService.findByUser(user);
		//遍历roles,返回这个用户所对应的角色
		for (Role role : roles) {
			authorizationInfo.addRole(role.getKeyword());
		}
		//根据user来查找这个user对应的权限
		List<Permission> permissions = permissionService.findByUser(user);
		for (Permission permission : permissions) {
			authorizationInfo.addStringPermission(permission.getKeyword());
		}
		return authorizationInfo;
	}

	@Override
	// 认证...
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationtoken)
			throws AuthenticationException {
		System.out.println("认证.............");
		// 将authenticationtoken转化为usernamePasswordToken
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationtoken;
		// 根据用户输入的用户名查找用户
		User user = userService.findByUsername(usernamePasswordToken.getUsername());
		if (user == null) {
			// 根据用户输入的用户名查找不到用户
			return null;
		} else {
			// 参数一：希望登录成功后,保存在subject中的信息
			// 参数二：将查询到的密码返回,入token中的密码匹配
			// 参数三:realm的名称
			return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
		}
	}

}
